/*
 * @Description: 监听器
 * @Author: wangqi
 * @Date: 2021-05-24 23:22:28
 * @LastEditTime: 2021-05-25 22:49:37
 */

import Dep from './Dep';

let uid = 0;
function parsePath(str) {
    let segments = str.split('.');
    return (obj) => {
        for (let i = 0; i < segments.length; i++) {
            if (!obj) return;
            obj = obj[segments[i]];
        }
        return obj;
    }
};

class Watcher {
    constructor(target, expression, callback) {
        this.id = uid++;
        this.target = target;
        this.getter = parsePath(expression);
        this.callback = callback;
        this.value = this.get();
    }

    get() {
        let value;
        Dep.target = this;
        const obj = this.target;
        try {
            value = this.getter(obj);
        } catch (error) {
            Dep.target = null;
        }
        return value;
    }

    update() {
        this.run();
    }

    run() {
        this.getAndInvoke(this.callback);
    }

    getAndInvoke(cb) {
        const value = this.get();

        if (value !== this.value || typeof value == 'object') {
            const oldValue = this.value;
            this.value = value;
            cb.call(this.target, value, oldValue);
        }
    }






}


export default Watcher;
